import { defineStore } from "pinia";
import { router } from "../router/index";

export const useLayoutStore = defineStore("layout", {
    state: () => {
        return {
            tags: {}, //打开的历史菜单标签 { idxxx:{与menu菜单保持一致,isActivity:false} }
            showTags: false, //是否展示tag标签页
            showBreadcrumb: true, //是否显示面包屑导航
            showFooter: true, //是否显示页面框架底部footer
            showLevel2MenuIcon: true, //是否展示二级菜单icon
            currentLevel1MenuKey: "", //当前活动的1级菜单key
            currentLevel2MenuKey: "", //当前活动的2级菜单页面key
        };
    },
    getters: {
        //当前活动tab的id
        currentActivityTagId() {
            for (let key in this.tags) {
                if (this.tags[key].isActivity) {
                    return key;
                }
            }
        },
    },
    actions: {
        // 仅仅在路由守卫处调用
        // toRoute = 前往的路由信息
        addTags(toRoute = {}) {
            let needAttr = ["path", "meta", "params"]; //tags中需要保存的数据
            let tagsData = {};
            needAttr.map((item) => {
                tagsData[item] = toRoute[item];
            });
            this.tags[toRoute.path] = tagsData;
            this.activationTag(toRoute.path);
        },
        //激活某个tag
        activationTag(toRoutePath = "") {
            for (let key in this.tags) {
                let item = this.tags[key];
                item.isActivity = false;
                if (item.path == toRoutePath) {
                    item.isActivity = true;
                }
            }
        },
        //移除tag
        removeTag(toRoutePath) {
            if (!this.tags[toRoutePath]) {
                return;
            }
            if (this.tags[toRoutePath].isActivity) {
                const keys = Object.keys(this.tags);
                if (keys.length > 0) {
                    const firstKey = keys[0];
                    this.tags[firstKey].isActivity = true;
                    router.push(this.tags[firstKey].path);
                }
            }
            delete this.tags[toRoutePath];
        },
    },
});
